package com.ruicar.afs.cloud.apply.pre.loan.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.apply.common.dto.ChannelInfoDTO;
import com.ruicar.afs.cloud.apply.common.entity.ApplyAffiliatedUnit;
import com.ruicar.afs.cloud.apply.common.entity.ApplyCarDetails;
import com.ruicar.afs.cloud.apply.common.entity.ApplyOprRecord;
import com.ruicar.afs.cloud.apply.common.entity.ApplyOrderInfo;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.pre.loan.condition.ApplyReportCondition;
import com.ruicar.afs.cloud.apply.pre.loan.condition.CarAffiliatedUnitCondition;
import com.ruicar.afs.cloud.apply.pre.loan.condition.CarInfoCondition;
import com.ruicar.afs.cloud.apply.pre.loan.service.*;
import com.ruicar.afs.cloud.apply.pre.loan.vo.CarInfoVO;
import com.ruicar.afs.cloud.apply.pre.loan.vo.CustomerListVO;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.parameter.commom.condition.VehicleCondition;
import com.ruicar.afs.cloud.vehicle.dto.CarInfoDto;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @description: 资产信息
 * @author: sijun.yu
 * @date: 2020/5/11 14:59
 */
@Slf4j
@RestController
@RequestMapping("/car")
@AllArgsConstructor
public class ApplyCarInfoController {

    private final ApplyCarDetailsService carInfoService;
    private final ApplyOrderInfoService applyOrderInfoService;
    private final ApplyOprRecordService applyOprRecordService;
    private final ApplyReportService reportService;
    private final ApplyAffiliatedUnitService applyAffiliatedUnitService;
    private final ApplyModifyHistoryService modifyHistoryService;

    /**
     * 查询资产信息
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "getCarInfo")
    @ApiOperation("查询资产信息")
    public IResponse<CustomerListVO> getCarInfo(@ModelAttribute ApplyReportCondition condition) {

        CarInfoVO vo = null;
        // 资产变更
        if("assetChange".equals(condition.getBusinessFlag())){
            vo = modifyHistoryService.getCarInfoForAssetChange(vo,condition);
            if(vo != null){
                return IResponse.success(vo);
            }
        }
        // 正常业务
        vo = carInfoService.getCarInfo(vo,condition);
        return IResponse.success(vo);
    }

    /**
     * 保存车辆信息
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/saveCarInfo")
    @ApiOperation("保存车辆信息")
    @Transactional
    @CacheEvict(value = "apply_car_details", allEntries = true)
    public IResponse saveCarInfo(@RequestBody CarInfoCondition condition) {

        String applyNo = condition.getApplyNo();
        ApplyCarDetails carDetails = reportService.saveOrUpdateCarInfo(applyNo, condition);
        return IResponse.success(carDetails);
    }

    /**
     * 保存车辆信息
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/updateCarInfo")
    @ApiOperation("更新车辆信息")
    @Transactional
    @CacheEvict(value = "apply_car_details", allEntries = true)
    public IResponse updateCarInfo(@RequestBody CarInfoCondition condition) {

        ApplyCarDetails carDetails = carInfoService.getById(condition.getId());
        if (carDetails == null) {
            return IResponse.fail("记录不存在");
        } else {
            reportService.saveOrUpdateCarInfo(condition.getApplyNo(), condition);
        }

        return IResponse.success(Boolean.TRUE).setMsg("更新成功");
    }

    /**
     * 二手车进件接口
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/getVinCarInfo")
    @ApiOperation("二手车进件接口")
    public IResponse usedCar(@ModelAttribute CarInfoCondition condition) {

        String vin = condition.getCarVin();
        return carInfoService.usedCar(vin);
    }

    /**
     * 估值价格
     * @param condition
     * @return
     */
    @ApiOperation("估值价格")
    @PostMapping(value = "/getValuationReport")
    public IResponse getValuationReport(@ModelAttribute CarInfoCondition condition){

        CarInfoDto dto = new CarInfoDto();
        dto.setVin(condition.getCarVin());
        dto.setStartDate((new Date()).getTime());
        dto.setEndDate((new Date()).getTime());
        JSONObject json = carInfoService.getValuationReport(dto);
        if (0 == json.getInteger("code")) {
            JSONArray jsonArray = json.getJSONArray("data");
            return IResponse.success(jsonArray.getJSONObject(0).getJSONObject("content").getBigDecimal("appraiseprice"));
        }
        return IResponse.success(BigDecimal.ZERO);
    }

    /**
     * 挂牌车查询
     *
     * @param condition
     * @return
     */
    @ApiOperation("挂牌车查询")
    @PostMapping("/getNameLib")
    public IResponse getNameLib(@RequestBody CarInfoCondition condition) {

        String vin = condition.getCarVin();
        return carInfoService.carListingSelecte(vin);
    }

    /**
     * 车架号是否已做过进件申请
     *
     * @param vin
     * @return
     */
    @ApiOperation("车架号是否已做过进件申请")
    @PostMapping("/isVinUsed")
    public Boolean isVinUsed(@RequestBody String vin) {
        ApplyCarDetails carDetails = this.carInfoService.getOne(Wrappers.<ApplyCarDetails>query().lambda()
                .eq(StringUtil.isNotEmpty(vin), ApplyCarDetails::getCarVin, vin).last("LIMIT 1"));
        if (ObjectUtil.isNotNull(carDetails)) {
            ApplyOrderInfo orderInfoByApplyNo = this.applyOrderInfoService.getOrderInfoByApplyNo(carDetails.getApplyNo());
            if (ObjectUtil.isNotNull(orderInfoByApplyNo)) {
                //如果订单状态为草稿，那么查询操作表，判断是否存在操作记录，如果存在，那么该订单一定做过进件申请，vin号被使用过
                if (orderInfoByApplyNo.getApplyStatus().equals(ApplyConstants.APPLY_STATUS_DRAFT)) {
                    List<ApplyOprRecord> list = this.applyOprRecordService.list(Wrappers.<ApplyOprRecord>query().lambda()
                            .eq(StringUtil.isNotEmpty(orderInfoByApplyNo.getApplyNo()), ApplyOprRecord::getApplyNo, orderInfoByApplyNo.getApplyNo()));
                    if (CollectionUtil.isNotEmpty(list)) {
                        return Boolean.FALSE;
                    }
                } else if (!orderInfoByApplyNo.getApplyStatus().equals(ApplyConstants.APPLY_STATUS_DRAFT)) {
                    //如果不是草稿状态，那么就说明，该订单做过进件申请，vin号被使用过
                    return Boolean.FALSE;
                }
            }
        }
        return Boolean.TRUE;
    }

    /**
     * 查询品牌列表
     * @param condition
     * @return
     */
    @PostMapping(value = "/getBrandList")
    @ApiOperation("查询品牌列表")
    public IResponse getBrandList(@ModelAttribute VehicleCondition condition){

        Assert.isTrue(condition.getBusinessType()!=null,"请选择业务类型");
        return carInfoService.getBrandList(condition);
    }

    /**
     * 查询车型列表
     * @param condition
     * @return
     */
    @PostMapping(value = "/getModelList")
    @ApiOperation("查询车型列表")
    public IResponse getModelList(@ModelAttribute VehicleCondition condition){

        Assert.isTrue(condition.getBusinessType()!=null,"请选择业务类型");
        return carInfoService.getModelList(condition);
    }

    /**
     * 查询车型列表 - 模糊
     * @param condition
     * @return
     */
    @PostMapping(value = "/getModelTitleList")
    @ApiOperation("查询车型列表 - 模糊")
    public IResponse getModelTitleList(@ModelAttribute VehicleCondition condition){

        Assert.isTrue(condition.getBusinessType()!=null,"请选择业务类型");
        return carInfoService.getModelTitleList(condition);
    }

    /**
     * 获取车商省份和城市
     * @param channelInfoDTO
     * @return
     */
    @PostMapping(value = "/getAuthorizeRegion")
    @ApiOperation("获取车商省份和城市")
    public IResponse getAuthorizeRegion(@RequestBody ChannelInfoDTO channelInfoDTO){

        return carInfoService.getAuthorizeRegion(channelInfoDTO);
    }

    /**
     * 查询资产信息 挂靠信息
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/getCarAffiliatedUnit")
    @ApiOperation("查询资产挂靠信息")
    public IResponse<CarAffiliatedUnitCondition> getCarAffiliatedUnit(@ModelAttribute ApplyReportCondition condition) {

        CarAffiliatedUnitCondition unitCondition = new CarAffiliatedUnitCondition();
        CarInfoVO vo = null;
        // 资产变更
        if("assetChange".equals(condition.getBusinessFlag())){
            vo = modifyHistoryService.getCarInfoForAssetChange(vo,condition);
            if(ObjectUtil.isNull(vo)){
                vo = carInfoService.getCarInfo(vo,condition);
            }
        }else{
            vo = carInfoService.getCarInfo(vo,condition);
        }
        unitCondition.setCarInfoVO(vo);
        ApplyAffiliatedUnit affiliatedUnit = applyAffiliatedUnitService.getAffiliatedUnitByApplyNo(condition.getApplyNo());
        if (affiliatedUnit != null) {
            unitCondition.setAffiliatedUnitVO(affiliatedUnit);
        }
        return IResponse.success(unitCondition);
    }

}
